/*
Copyright (C) 2009  Diego Darriba

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
package es.uvigo.darwin.xprottest.analysis.consensus;

import es.uvigo.darwin.prottest.util.logging.ProtTestLogger;
import es.uvigo.darwin.prottest.util.printer.ProtTestPrinter;
import static es.uvigo.darwin.prottest.global.ApplicationGlobals.*;

import es.uvigo.darwin.prottest.facade.TreeFacade;
import es.uvigo.darwin.prottest.model.Model;
import es.uvigo.darwin.prottest.selection.AIC;
import es.uvigo.darwin.prottest.selection.AICc;
import es.uvigo.darwin.prottest.selection.BIC;
import es.uvigo.darwin.prottest.selection.DT;
import es.uvigo.darwin.prottest.selection.InformationCriterion;
import es.uvigo.darwin.prottest.selection.LNL;
import es.uvigo.darwin.prottest.util.ProtTestAlignment;
import es.uvigo.darwin.prottest.util.collection.ModelCollection;
import es.uvigo.darwin.prottest.util.collection.SingleModelCollection;
import es.uvigo.darwin.prottest.util.exception.ProtTestInternalException;
import java.awt.Font;
import pal.tree.Tree;
import java.io.PrintWriter;
import org.jdesktop.application.Action;
import org.jdesktop.application.Application;
import org.jdesktop.application.ResourceMap;
import es.uvigo.darwin.xprottest.XProtTestView;
import es.uvigo.darwin.xprottest.util.TextAreaWriter;
import java.util.logging.Handler;
import java.util.logging.Level;
import pal.alignment.Alignment;
import pal.misc.Identifier;

import static es.uvigo.darwin.prottest.util.logging.ProtTestLogger.*;

/**
 *
 * @author  diego
 */
public class Consensus extends javax.swing.JFrame {

    private static final int AIC_SELECTION = 0;
    private static final int BIC_SELECTION = 1;
    private static final int AICC_SELECTION = 2;
    private static final int LNL_SELECTION = 3;
    private static final int DT_SELECTION = 4;
    private static final int DISABLED_SELECTION = 5;
    private static final String[] SELECTION = {
        "AIC", "BIC", "AICc", "LK", "DT", "Disabled"
    };
    private ResourceMap resourceMap;
    private TreeFacade facade;
    private ModelCollection models;
    private Handler logHandler;
    private PrintWriter displayWriter;
    private int sampleSizeMode = DEFAULT_SAMPLE_SIZE_MODE;
    private double sampleSize = 1.0;
    private XProtTestView mainFrame;

    /** Creates new form Consensus */
    public Consensus(XProtTestView mainFrame, TreeFacade facade, Model[] models, Alignment alignment) {
        initComponents();
        this.mainFrame = mainFrame;
        this.facade = facade;
        this.models = new SingleModelCollection(models, alignment);
        this.displayWriter = new PrintWriter(new TextAreaWriter(displayArea));
        this.logHandler = getDefaultLogger().addHandler(displayWriter, Level.OFF);

        resourceMap = Application.getInstance(es.uvigo.darwin.xprottest.XProtTestApp.class).getContext().getResourceMap(Consensus.class);

        Font f = new Font(Font.MONOSPACED, Font.PLAIN, 12);
        displayArea.setFont(f);
        lblSampleSize.setText(String.valueOf(ProtTestAlignment.calculateSampleSize(this.models.getAlignment(), sampleSizeMode, sampleSize)));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnGrpCriterion = new javax.swing.ButtonGroup();
        btnGroupSampleSizeMode = new javax.swing.ButtonGroup();
        settingsPanel = new javax.swing.JPanel();
        lblTitle = new javax.swing.JLabel();
        lblCriterion = new javax.swing.JLabel();
        radioAIC = new javax.swing.JRadioButton();
        radioBIC = new javax.swing.JRadioButton();
        radioAICC = new javax.swing.JRadioButton();
        radioDT = new javax.swing.JRadioButton();
        radioLK = new javax.swing.JRadioButton();
        sliderConsType = new javax.swing.JSlider();
        lblConsType = new javax.swing.JLabel();
        btnBuild = new javax.swing.JButton();
        lblMR = new javax.swing.JLabel();
        lblStrict = new javax.swing.JLabel();
        lblConfInt = new javax.swing.JLabel();
        sliderConfidence = new javax.swing.JSlider();
        lblConfidenceInterval = new javax.swing.JLabel();
        lblConsensusType = new javax.swing.JLabel();
        lblPercent = new javax.swing.JLabel();
        sizeModeAlignment3 = new javax.swing.JRadioButton();
        sizeModeNL = new javax.swing.JRadioButton();
        sizeModeCustom = new javax.swing.JRadioButton();
        txtSampleSize = new javax.swing.JTextField();
        sizeModeVar = new javax.swing.JRadioButton();
        sizeModeShannon = new javax.swing.JRadioButton();
        sizeModeShannonNL = new javax.swing.JRadioButton();
        lblSampleSize = new javax.swing.JLabel();
        lblSampleSizeMode = new javax.swing.JLabel();
        btnExport = new javax.swing.JButton();
        displayScroll = new javax.swing.JScrollPane();
        displayArea = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        windowMenu = new javax.swing.JMenu();
        closeMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        editCopyMenuItem = new javax.swing.JMenuItem();
        selectAllMenuItem = new javax.swing.JMenuItem();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(Consensus.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        settingsPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        settingsPanel.setName("settingsPanel"); // NOI18N

        lblTitle.setBackground(resourceMap.getColor("lblTitle.background")); // NOI18N
        lblTitle.setFont(resourceMap.getFont("lblTitle.font")); // NOI18N
        lblTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblTitle.setText(resourceMap.getString("title.text")); // NOI18N
        lblTitle.setName("lblTitle"); // NOI18N

        lblCriterion.setText(resourceMap.getString("lblCriterion.text")); // NOI18N
        lblCriterion.setName("lblCriterion"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(Consensus.class, this);
        radioAIC.setAction(actionMap.get("disableSampleSize")); // NOI18N
        btnGrpCriterion.add(radioAIC);
        radioAIC.setText(resourceMap.getString("radioAIC.text")); // NOI18N
        radioAIC.setName("radioAIC"); // NOI18N

        radioBIC.setAction(actionMap.get("enableSampleSize")); // NOI18N
        btnGrpCriterion.add(radioBIC);
        radioBIC.setText(resourceMap.getString("radioBIC.text")); // NOI18N
        radioBIC.setName("radioBIC"); // NOI18N

        radioAICC.setAction(actionMap.get("enableSampleSize")); // NOI18N
        btnGrpCriterion.add(radioAICC);
        radioAICC.setText(resourceMap.getString("radioAICC.text")); // NOI18N
        radioAICC.setName("radioAICC"); // NOI18N

        radioDT.setAction(actionMap.get("disableSampleSize")); // NOI18N
        btnGrpCriterion.add(radioDT);
        radioDT.setSelected(true);
        radioDT.setText(resourceMap.getString("radioDT.text")); // NOI18N
        radioDT.setName("radioDT"); // NOI18N

        radioLK.setAction(actionMap.get("disableSampleSize")); // NOI18N
        btnGrpCriterion.add(radioLK);
        radioLK.setText(resourceMap.getString("radioLK.text")); // NOI18N
        radioLK.setName("radioLK"); // NOI18N

        sliderConsType.setMinimum(50);
        sliderConsType.setToolTipText(resourceMap.getString("sliderConsType.toolTipText")); // NOI18N
        sliderConsType.setName("sliderConsType"); // NOI18N
        sliderConsType.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                sliderConsTypeStateChanged(evt);
            }
        });

        lblConsType.setText(resourceMap.getString("lblConsType.text")); // NOI18N
        lblConsType.setName("lblConsType"); // NOI18N

        btnBuild.setAction(actionMap.get("buildConsensus")); // NOI18N
        btnBuild.setText(resourceMap.getString("btnBuild.text")); // NOI18N
        btnBuild.setName("btnBuild"); // NOI18N

        lblMR.setFont(resourceMap.getFont("lblMR.font")); // NOI18N
        lblMR.setForeground(resourceMap.getColor("lblMR.foreground")); // NOI18N
        lblMR.setText(resourceMap.getString("lblMR.text")); // NOI18N
        lblMR.setName("lblMR"); // NOI18N

        lblStrict.setFont(resourceMap.getFont("lblStrict.font")); // NOI18N
        lblStrict.setForeground(resourceMap.getColor("lblStrict.foreground")); // NOI18N
        lblStrict.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblStrict.setText(resourceMap.getString("lblStrict.text")); // NOI18N
        lblStrict.setName("lblStrict"); // NOI18N

        lblConfInt.setText(resourceMap.getString("lblConfInt.text")); // NOI18N
        lblConfInt.setToolTipText(resourceMap.getString("lblConfInt.toolTipText")); // NOI18N
        lblConfInt.setName("lblConfInt"); // NOI18N

        sliderConfidence.setValue(100);
        sliderConfidence.setName("sliderConfidence"); // NOI18N
        sliderConfidence.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                sliderConfidenceStateChanged(evt);
            }
        });

        lblConfidenceInterval.setText(resourceMap.getString("default-confidence-interval")); // NOI18N
        lblConfidenceInterval.setName("lblConfidenceInterval"); // NOI18N

        lblConsensusType.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblConsensusType.setText(resourceMap.getString("default-consensus-type")); // NOI18N
        lblConsensusType.setName("lblConsensusType"); // NOI18N

        lblPercent.setText(resourceMap.getString("percent-symbol")); // NOI18N
        lblPercent.setName("lblPercent"); // NOI18N

        sizeModeAlignment3.setAction(actionMap.get("selectSampleSize")); // NOI18N
        btnGroupSampleSizeMode.add(sizeModeAlignment3);
        sizeModeAlignment3.setSelected(true);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("es/uvigo/darwin/xprottest/results/resources/ResultsView"); // NOI18N
        sizeModeAlignment3.setText(bundle.getString("btn-sizemode-alignment")); // NOI18N
        sizeModeAlignment3.setToolTipText(resourceMap.getString("sizeModeAlignment3.toolTipText")); // NOI18N
        sizeModeAlignment3.setName("sizeModeAlignment3"); // NOI18N
        sizeModeAlignment3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sizeModePressed(evt);
            }
        });

        sizeModeNL.setAction(actionMap.get("selectSampleSize")); // NOI18N
        btnGroupSampleSizeMode.add(sizeModeNL);
        sizeModeNL.setText(bundle.getString("btn-sizemode-nxl")); // NOI18N
        sizeModeNL.setToolTipText(resourceMap.getString("sizeModeNL.toolTipText")); // NOI18N
        sizeModeNL.setName("sizeModeNL"); // NOI18N
        sizeModeNL.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sizeModePressed(evt);
            }
        });

        sizeModeCustom.setAction(actionMap.get("selectSampleSize")); // NOI18N
        btnGroupSampleSizeMode.add(sizeModeCustom);
        sizeModeCustom.setText(bundle.getString("btn-sizemode-custom")); // NOI18N
        sizeModeCustom.setToolTipText(resourceMap.getString("sizeModeCustom.toolTipText")); // NOI18N
        sizeModeCustom.setName("sizeModeCustom"); // NOI18N
        sizeModeCustom.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sizeModePressed(evt);
            }
        });

        txtSampleSize.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtSampleSize.setText(resourceMap.getString("txtSampleSize.text")); // NOI18N
        txtSampleSize.setEnabled(false);
        txtSampleSize.setName("txtSampleSize"); // NOI18N
        txtSampleSize.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtSampleSizeFocusLost(evt);
            }
        });

        sizeModeVar.setAction(actionMap.get("selectSampleSize")); // NOI18N
        btnGroupSampleSizeMode.add(sizeModeVar);
        sizeModeVar.setText(bundle.getString("btn-sizemode-alignment-var")); // NOI18N
        sizeModeVar.setToolTipText(resourceMap.getString("sizeModeVar.toolTipText")); // NOI18N
        sizeModeVar.setName("sizeModeVar"); // NOI18N
        sizeModeVar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sizeModePressed(evt);
            }
        });

        sizeModeShannon.setAction(actionMap.get("selectSampleSize")); // NOI18N
        btnGroupSampleSizeMode.add(sizeModeShannon);
        sizeModeShannon.setText(bundle.getString("btn-sizemode-shannon")); // NOI18N
        sizeModeShannon.setToolTipText(resourceMap.getString("sizeModeShannon.toolTipText")); // NOI18N
        sizeModeShannon.setName("sizeModeShannon"); // NOI18N
        sizeModeShannon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sizeModePressed(evt);
            }
        });

        sizeModeShannonNL.setAction(actionMap.get("selectSampleSize")); // NOI18N
        btnGroupSampleSizeMode.add(sizeModeShannonNL);
        sizeModeShannonNL.setText(bundle.getString("btn-sizemode-shannon-nxl")); // NOI18N
        sizeModeShannonNL.setToolTipText(resourceMap.getString("sizeModeShannonNL.toolTipText")); // NOI18N
        sizeModeShannonNL.setName("sizeModeShannonNL"); // NOI18N
        sizeModeShannonNL.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sizeModePressed(evt);
            }
        });

        lblSampleSize.setText(resourceMap.getString("lblSampleSize.text")); // NOI18N
        lblSampleSize.setName("lblSampleSize"); // NOI18N

        lblSampleSizeMode.setText(resourceMap.getString("lblSampleSizeMode.text")); // NOI18N
        lblSampleSizeMode.setName("lblSampleSizeMode"); // NOI18N

        btnExport.setAction(actionMap.get("exportData")); // NOI18N
        btnExport.setText(resourceMap.getString("btnExport.text")); // NOI18N
        btnExport.setEnabled(false);
        btnExport.setName("btnExport"); // NOI18N

        javax.swing.GroupLayout settingsPanelLayout = new javax.swing.GroupLayout(settingsPanel);
        settingsPanel.setLayout(settingsPanelLayout);
        settingsPanelLayout.setHorizontalGroup(
            settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(settingsPanelLayout.createSequentialGroup()
                .addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(settingsPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblCriterion, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
                            .addGroup(settingsPanelLayout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(radioAIC)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(radioBIC)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(radioAICC)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(radioDT)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(radioLK))
                            .addGroup(settingsPanelLayout.createSequentialGroup()
                                .addComponent(lblConsType)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblConsensusType, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblPercent))
                            .addComponent(sliderConsType, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
                            .addGroup(settingsPanelLayout.createSequentialGroup()
                                .addComponent(lblMR, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(129, 129, 129)
                                .addComponent(btnBuild)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnExport)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 182, Short.MAX_VALUE)
                                .addComponent(lblStrict, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(sliderConfidence, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 636, Short.MAX_VALUE)
                            .addGroup(settingsPanelLayout.createSequentialGroup()
                                .addComponent(lblConfInt)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblConfidenceInterval))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, settingsPanelLayout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(settingsPanelLayout.createSequentialGroup()
                                .addComponent(sizeModeAlignment3)
                                .addGap(15, 15, 15))
                            .addComponent(sizeModeNL, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, settingsPanelLayout.createSequentialGroup()
                                .addComponent(sizeModeCustom, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtSampleSize, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, settingsPanelLayout.createSequentialGroup()
                                .addComponent(sizeModeVar, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(sizeModeShannon, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(sizeModeShannonNL, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(lblSampleSize, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 504, Short.MAX_VALUE)))
                    .addGroup(settingsPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblSampleSizeMode, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        settingsPanelLayout.setVerticalGroup(
            settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(settingsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblTitle)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblCriterion)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioAIC)
                    .addComponent(radioBIC)
                    .addComponent(radioAICC)
                    .addComponent(radioDT)
                    .addComponent(radioLK))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblSampleSize)
                    .addComponent(lblSampleSizeMode))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sizeModeAlignment3)
                    .addComponent(sizeModeShannonNL)
                    .addComponent(sizeModeShannon)
                    .addComponent(sizeModeVar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sizeModeNL)
                    .addComponent(sizeModeCustom)
                    .addComponent(txtSampleSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 6, Short.MAX_VALUE)
                .addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblConfInt)
                    .addComponent(lblConfidenceInterval))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sliderConfidence, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblConsType)
                    .addComponent(lblConsensusType)
                    .addComponent(lblPercent))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sliderConsType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblMR)
                    .addComponent(lblStrict)
                    .addGroup(settingsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btnBuild)
                        .addComponent(btnExport)))
                .addContainerGap())
        );

        displayScroll.setName("displayScroll"); // NOI18N

        displayArea.setColumns(20);
        displayArea.setEditable(false);
        displayArea.setLineWrap(true);
        displayArea.setRows(5);
        displayArea.setName("displayArea"); // NOI18N
        displayScroll.setViewportView(displayArea);

        jMenuBar1.setName("jMenuBar1"); // NOI18N

        windowMenu.setName("windowMenu"); // NOI18N

        closeMenuItem.setAction(actionMap.get("Close")); // NOI18N
        closeMenuItem.setName("closeMenuItem"); // NOI18N
        windowMenu.add(closeMenuItem);

        jMenuBar1.add(windowMenu);

        editMenu.setText(resourceMap.getString("editMenu.text")); // NOI18N
        editMenu.setName("editMenu"); // NOI18N

        editCopyMenuItem.setAction(actionMap.get("editCopy")); // NOI18N
        editCopyMenuItem.setName("editCopyMenuItem"); // NOI18N
        editMenu.add(editCopyMenuItem);

        selectAllMenuItem.setAction(actionMap.get("editSelectAll")); // NOI18N
        selectAllMenuItem.setText(resourceMap.getString("selectAllMenuItem.text")); // NOI18N
        selectAllMenuItem.setName("selectAllMenuItem"); // NOI18N
        editMenu.add(selectAllMenuItem);

        jMenuBar1.add(editMenu);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(displayScroll, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 664, Short.MAX_VALUE)
                    .addComponent(settingsPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(settingsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(displayScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void sliderConfidenceStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_sliderConfidenceStateChanged
        lblConfidenceInterval.setText(String.valueOf(Double.valueOf(sliderConfidence.getValue()) / 100));
    }//GEN-LAST:event_sliderConfidenceStateChanged

    private void sliderConsTypeStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_sliderConsTypeStateChanged
        lblConsensusType.setText(String.valueOf(Double.valueOf(sliderConsType.getValue()) / 100));
    }//GEN-LAST:event_sliderConsTypeStateChanged

    private void sizeModePressed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sizeModePressed

        String btnName = evt.getActionCommand();

        txtSampleSize.setEnabled(false);
        if (btnName.equals(
                java.util.ResourceBundle.getBundle("es/uvigo/darwin/xprottest/results/resources/ResultsView").getString("btn-sizemode-alignment"))) {
            sampleSizeMode = SIZEMODE_ALIGNMENT;
        } else if (btnName.equals(
                java.util.ResourceBundle.getBundle("es/uvigo/darwin/xprottest/results/resources/ResultsView").getString("btn-sizemode-alignment-var"))) {
            sampleSizeMode = SIZEMODE_ALIGNMENT_VAR;
        } else if (btnName.equals(
                java.util.ResourceBundle.getBundle("es/uvigo/darwin/xprottest/results/resources/ResultsView").getString("btn-sizemode-shannon"))) {
            sampleSizeMode = SIZEMODE_SHANNON;
        } else if (btnName.equals(
                java.util.ResourceBundle.getBundle("es/uvigo/darwin/xprottest/results/resources/ResultsView").getString("btn-sizemode-shannon-nxl"))) {
            sampleSizeMode = SIZEMODE_SHANNON_NxL;
        } else if (btnName.equals(
                java.util.ResourceBundle.getBundle("es/uvigo/darwin/xprottest/results/resources/ResultsView").getString("btn-sizemode-nxl"))) {
            sampleSizeMode = SIZEMODE_NxL;
        } else if (btnName.equals(
                java.util.ResourceBundle.getBundle("es/uvigo/darwin/xprottest/results/resources/ResultsView").getString("btn-sizemode-custom"))) {
            sampleSizeMode = SIZEMODE_USERSIZE;
            try {
                sampleSize = Double.parseDouble(txtSampleSize.getText());
            } catch (NumberFormatException e) {
                sampleSize = 0.0;
            }
            txtSampleSize.setEnabled(true);
            txtSampleSize.grabFocus();
        }
        lblSampleSize.setText(String.valueOf(ProtTestAlignment.calculateSampleSize(models.getAlignment(), sampleSizeMode, sampleSize)));
    }//GEN-LAST:event_sizeModePressed

    private void txtSampleSizeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtSampleSizeFocusLost
        try {
            sampleSize = Double.parseDouble(txtSampleSize.getText());
        } catch (NumberFormatException e) {
            sampleSize = 0.0;
        }
        lblSampleSize.setText(String.valueOf(ProtTestAlignment.calculateSampleSize(models.getAlignment(), sampleSizeMode, sampleSize)));
    }//GEN-LAST:event_txtSampleSizeFocusLost

    @Action
    public void buildConsensus() {
        displayArea.setText("");
        displayArea.setForeground(XProtTestView.NORMAL_COLOR);
        double confidenceInterval = Double.valueOf(sliderConfidence.getValue()) / 100;
        double supportThreshold = Double.valueOf(sliderConsType.getValue()) / 100;
        try {
//            double sampleSize = 0.0;
//            if (txtSampleSize.isEnabled()) {
//                sampleSize = Double.valueOf(txtSampleSize.getText());
//            }
            InformationCriterion ic;
            int selection;
            if (radioAIC.isSelected()) {
                ic = new AIC(models, confidenceInterval, sampleSize);
                selection = AIC_SELECTION;
            } else if (radioBIC.isSelected()) {
                ic = new BIC(models, confidenceInterval, sampleSize);
                selection = BIC_SELECTION;
            } else if (radioAICC.isSelected()) {
                ic = new AICc(models, confidenceInterval, sampleSize);
                selection = AICC_SELECTION;
            } else if (radioLK.isSelected()) {
                ic = new LNL(models, confidenceInterval, sampleSize);
                selection = LNL_SELECTION;
            } else if (radioDT.isSelected()) {
                ic = new DT(models, confidenceInterval, sampleSize);
                selection = DT_SELECTION;
            } else {
                ic = null;
                selection = DISABLED_SELECTION;
            }

            logHandler.setLevel(Level.INFO);

            if (ic == null || ic.getConfidenceModels().size() > 0) {
                es.uvigo.darwin.prottest.consensus.Consensus consensus = null;
                if (ic != null) {
                    consensus = facade.createConsensus(ic, supportThreshold);
                } else {
                    throw new ProtTestInternalException("Consensus needs an Information Criterion");
//                    ArrayList<Tree> trees = new ArrayList<Tree>(models.size());
//                    for (Model model : models) {
//                        trees.add(model.getTree());
//                    }
//                    consensus = facade.createConsensus(trees, supportThreshold);
                }
                println("----------------------------------------");
                println("Selection criterion: . . . . " + SELECTION[selection]);
                println("Confidence interval: . . . . " + confidenceInterval);
                println("Sample size: . . . . . . . . " + sampleSize);
                println("Consensus support threshold: " + supportThreshold);
                println("----------------------------------------");

//                displayWriter.println("Computed models:");
//                for (SelectionModel model : ic.getConfidenceModels()) {
//                    displayWriter.println(model.getModel().getModelName() + " (" + model.getWeightValue() + ")");
//                }
//                displayWriter.println("----------------------------------------");

                println("");

                println("# # # # # # # # # # # # # # # #");
                println(" ");
                println("Species in order:");
                println(" ");

                for (int i = 0; i < consensus.getIdGroup().getIdCount(); i++) {
                    Identifier id = consensus.getIdGroup().getIdentifier(i);
                    println("    " + (i + 1) + ". " + id.getName());
                }
                println(" ");
                println("# # # # # # # # # # # # # # # #");
                println(" ");
                println("Sets included in the consensus tree");
                println(" ");

                int numTaxa = consensus.getIdGroup().getIdCount();
                println(consensus.getSetsIncluded());
                
                println(" ");
                println("Sets NOT included in consensus tree");
                println(" ");

                println(consensus.getSetsNotIncluded());

                println(" ");
                println("# # # # # # # # # # # # # # # #");
                println(" ");

                Tree consensusTree = consensus.getConsensusTree();
                String newickTree = facade.toNewick(consensusTree, true, true, true);
                println(newickTree);

                println(" ");
                println("# # # # # # # # # # # # # # # #");
                println(" ");

                println(facade.toASCII(consensusTree));
                println(" ");
                println(facade.branchInfo(consensusTree));
                println(" ");
                println(facade.heightInfo(consensusTree));
            } else {
                displayArea.setForeground(XProtTestView.CRITIC_COLOR);
                println(resourceMap.getString("msg-no-data"));
            }
        } catch (NumberFormatException e) {
            displayArea.setForeground(XProtTestView.CRITIC_COLOR);
            println(resourceMap.getString("msg-sample-size-error"));
        }
        logHandler.setLevel(Level.OFF);
        btnExport.setEnabled(!displayArea.getText().equals(""));
    }

    @Action
    public void disableSampleSize() {
        txtSampleSize.setEnabled(false);
    }

    @Action
    public void enableSampleSize() {
        txtSampleSize.setEnabled(true);
    }

    @Action
    public void close() {
        getDefaultLogger().removeHandler(logHandler);
        this.setVisible(false);
    }

    @Action
    public void editCopy() {
        displayArea.copy();
    }

    @Action
    public void editSelectAll() {
        displayArea.selectAll();
    }

    @Action
    public void selectSampleSize() {
    }

    private void print(String message) {
        info(message, this.getClass());
    }

    private void println(String message) {
        infoln(message, this.getClass());
    }

    @Action
    public void exportData() {
        mainFrame.enableHandler();
        ProtTestPrinter.printTreeHeader("MODEL AVERAGED PHYLOGENY");
        ProtTestLogger.getDefaultLogger().infoln(displayArea.getText());
        mainFrame.disableHandler();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuild;
    private javax.swing.JButton btnExport;
    private javax.swing.ButtonGroup btnGroupSampleSizeMode;
    private javax.swing.ButtonGroup btnGrpCriterion;
    private javax.swing.JMenuItem closeMenuItem;
    private javax.swing.JTextArea displayArea;
    private javax.swing.JScrollPane displayScroll;
    private javax.swing.JMenuItem editCopyMenuItem;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JLabel lblConfInt;
    private javax.swing.JLabel lblConfidenceInterval;
    private javax.swing.JLabel lblConsType;
    private javax.swing.JLabel lblConsensusType;
    private javax.swing.JLabel lblCriterion;
    private javax.swing.JLabel lblMR;
    private javax.swing.JLabel lblPercent;
    private javax.swing.JLabel lblSampleSize;
    private javax.swing.JLabel lblSampleSizeMode;
    private javax.swing.JLabel lblStrict;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JRadioButton radioAIC;
    private javax.swing.JRadioButton radioAICC;
    private javax.swing.JRadioButton radioBIC;
    private javax.swing.JRadioButton radioDT;
    private javax.swing.JRadioButton radioLK;
    private javax.swing.JMenuItem selectAllMenuItem;
    private javax.swing.JPanel settingsPanel;
    private javax.swing.JRadioButton sizeModeAlignment3;
    private javax.swing.JRadioButton sizeModeCustom;
    private javax.swing.JRadioButton sizeModeNL;
    private javax.swing.JRadioButton sizeModeShannon;
    private javax.swing.JRadioButton sizeModeShannonNL;
    private javax.swing.JRadioButton sizeModeVar;
    private javax.swing.JSlider sliderConfidence;
    private javax.swing.JSlider sliderConsType;
    private javax.swing.JTextField txtSampleSize;
    private javax.swing.JMenu windowMenu;
    // End of variables declaration//GEN-END:variables
}
